package controller

import (
	"mygame/app/common/ret"
	"mygame/app/services"
	reqdata "mygame/app/structs/reqData"
	"strings"

	"github.com/gin-gonic/gin"
)

type User struct{}

func (User) Login(c *gin.Context) {
	var data reqdata.Login
	if err := c.ShouldBindJSON(&data); err != nil {
		ret.Error(c, err.Error())
		return
	}

	res, err := services.User{}.UsernameLogin(data.Username, data.Password)
	if err != nil {
		ret.Error(c, err.Error())
		return
	}

	ret.Success(c, res)
}

func (User) WxLogin(c *gin.Context) {
	data := GetRawData(c)
	if data["code"] == nil {
		ret.Error(c, "code is nil")
		return
	}

	// 测试登录
	if strings.HasPrefix(data["code"].(string), "test") {
		res, err := services.User{}.OpenidLogin(data["code"].(string))
		if err != nil {
			ret.Error(c, err.Error())
			return
		}
		ret.Success(c, res)
		return
	}

	openid, err := services.Weixin{}.GetOpenid(data["code"].(string))
	if err != nil {
		ret.Error(c, err.Error())
		return
	}
	res, err := services.User{}.OpenidLogin(openid)
	if err != nil {
		ret.Error(c, err.Error())
		return
	}
	ret.Success(c, res)
}

func (User) Info(ctx *gin.Context) {
	uid, err := ctx.Get("userId")
	if !err {
		ret.Error(ctx, "获取用户信息失败")
	}

	// 获取用户信息
	user := services.User{}.GetUserInfo(uid.(int64))

	ret.Success(ctx, user)
}

func (User) SyncData(ctx *gin.Context) {
	uid, err := ctx.Get("userId")
	if !err {
		ret.Error(ctx, "获取用户信息失败")
	}
	raw := GetRawData(ctx)
	services.User{}.SaveData(uid.(int64), raw)
	ret.Success(ctx, nil)
}

func (User) GetData(ctx *gin.Context) {
	uid, err := ctx.Get("userId")
	if !err {
		ret.Error(ctx, "获取用户信息失败")
	}
	data := services.User{}.GetData(uid.(int64))
	ret.Success(ctx, data)
}
